package com.sc.ktapplication

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.sc.ktapplication.common.constant.MMKVConstant
import com.sc.ktapplication.common.util.MMKVUtil
import com.sc.ktapplication.module.entity.AppUser
import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kotlin.system.exitProcess

class MyApp : Application() {

    companion object{
        var activities : ArrayList<Activity> = ArrayList()
        lateinit var instance : MyApp
        lateinit var user: AppUser
    }

    override fun onCreate(){
        super.onCreate()
        instance = this
        MMKV.initialize(this)
        ARouter.init(this)
        initUmeng()
        closeAndroidPDialog()
    }

    fun getUser(): AppUser? {
        val userStr = MMKVUtil.getString(MMKVConstant.APP_USER)
        if(!TextUtils.isEmpty(userStr)){
            user  = JSON.parseObject(userStr,AppUser::class.java)
            return user
        }
        return null
    }

    fun addActivity(activity: Activity){
        activities.add(activity)
    }

    fun removeActivity(activity: Activity){
        activities.remove(activity)
    }

    fun exit(){
        for (activity in activities)
            activity.finish()
        android.os.Process.killProcess(android.os.Process.myPid())
        exitProcess(0)
    }


    private fun closeAndroidPDialog() {
        try {
            val aClass = Class.forName("android.content.pm.PackageParser\$Package")
            val declaredConstructor = aClass.getDeclaredConstructor(String::class.java)
            declaredConstructor.isAccessible = true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            val cls = Class.forName("android.app.ActivityThread")
            val declaredMethod = cls.getDeclaredMethod("currentActivityThread")
            declaredMethod.isAccessible = true
            val activityThread = declaredMethod.invoke(null)
            val mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown")
            mHiddenApiWarningShown.isAccessible = true
            mHiddenApiWarningShown.setBoolean(activityThread, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initUmeng() {
        UMConfigure.init(this, "5fc34cd153a0037e2850e9ba","Umeng", UMConfigure.DEVICE_TYPE_PHONE, "")
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
    }
}